var $ = window.$;
var frac = require('../../../util/frac');
var event = require('../../../core/event');
var sound = require('../../audio/sound');
var sample = require('../../sample/manager');
var timing = require('../../timing/manager');
var Log = require('../../../util/logger');


var ret = {
    setUI: function (_ui) {
        this.ui = _ui;
    },

    onCancel: function(){
        //this.select = null;
    },

    onCopy: function(){
        this.onBeforeCopy();
        this.select = this.ui.note.find('.curr');
        Log.i("copy note:"+this.select.size());
    },

    /**
     * 如果选择了hold或者rain中的一个 则整体选择
     */
    onBeforeCopy : function(){
        var selected = this.ui.note.children(".curr");
        var processed = {};
        for(var i=0; i<selected.length;i++){
            var note = $(selected[i]);
            var id = note.attr("data-tag");
            if(processed[id]){
                continue;
            }
            if(note.hasClass("spinner_anchor") || note.hasClass("hold_node")){
                var result = this.ui.selectChainNotes(note);
                for(var j=0;j<result.length;j++){
                    processed[result[j].id] = true;
                }
            }
        }
    },

    /**
     * 拷贝之后修复hold和rain之间的连接线
     * @param args
     */
    onAfterPaste : function(args){
        var new2old = args.mapping;
        var old2new = {};
        var oldId, note, oldNote, nextNote, newDiv;
        var s = "";
        for(var k in new2old){
            old2new[new2old[k]] = +k;
        }
        //使用拷贝前的note重建拷贝后note的关联
        for(var k in new2old){
            oldId = new2old[k];
            note = this.manager.getNote(k);
            oldNote = this.manager.getNote(oldId);
            newDiv = this.getNoteDiv(k);
            if(oldNote.prev > 0){
                note.prev = +old2new[oldNote.prev];
            }
            if(oldNote.next > 0){
                note.next = +old2new[oldNote.next];
                nextNote = this.manager.getNote(old2new[oldNote.next]);
                note._endbeat = nextNote.beat;
                note.endx = nextNote.x;
            }
            if(oldNote.prev > 0 || oldNote.next > 0){
                newDiv.addClass(oldNote.type == this.TYPE_RAIN ? "spinner_anchor" : "hold_node");
            }
        }
        for(var k in new2old){
            note = this.manager.getNote(k);
            if(note.next > 0){
                nextNote = this.manager.getNote(note.next);
                if(note.type != this.TYPE_RAIN){
                    s += this.getNoteHoldLineDiv(note, nextNote);
                }else{
                    s += this.getSpinnerMaskDiv(note, nextNote);
                }
            }
        }
        this.note.append(s);
    },

    onPaste: function () {
        if(!this.select){
            Log.i("paste note: 0!!");
            return;
        }
        Log.i("paste note:"+this.select.size());

        //1. 当前时间对应的beat值, 对齐栅格
        var beat = this.ui.getGridBottomBeat();
        //2. 找到选中note最小beat值
        var notes = [];
        var len = this.select.length;
        var _min = [99999999, 0, 1];  //要能比这beat还大我就吃键盘
        for(var i=0;i<len;i++){
            var _id = +this.select.eq(i).data('tag');
            var _note = this.ui.manager.getNote(_id);
            notes.push(_note); //为了省事, notes和select完全对应
            if(frac.compare(_note.beat, _min) < 0){
                _min = _note.beat;
            }
        }
        //去掉旧选中
        this.ui.note.find('.curr').removeClass('curr');
        //3. 计算beat差, 全部note加上这个差值
        var delta = frac.subtract(beat, _min);
        var mapping = {}; //记录复制前后的id映射关系 ctb修复hold和rain时需要
        for(var i=0;i<len;i++){
            var _note = this.ui.manager.copyNote(notes[i]);
            _note.beat = frac.add(_note.beat, delta);
            if(_note.endbeat){
                _note.endbeat = frac.add(_note.endbeat, delta);
            }
            var id = this.ui.manager.addNote(_note);
            mapping[id] = notes[i].id;
            var html = $('<div class="curr" data-tag="'+id+'"></div>');
            var color = this.select.eq(i).css('backgroundColor');
            if(color){
                html.css('backgroundColor', color);
            }

            var time = timing.beatToTime(_note.beat) + (_note.offset || 0);
            //重载音频
            if(_note.sound){
                _note.tid = sound.addCell(sample.getFilePath(_note.sound), _note.vol || 30, 0);
                if(_note.tid >= 0){
                    sound.offsetCell(_note.tid, time);
                }
            }

            this.ui.note.append(html);
            this.ui.alignNote(_note, html);

            this.ui.checkMaxTime(time);
        }
        this.onAfterPaste.apply(this.ui, [{mapping : mapping}]);
        event.trigger(event.events.note.change);
    },

    onCut: function(){
        if(!this.select){
            return;
        }
        //1. 当前时间对应的beat值, 对齐栅格
        var beat = this.ui.getGridBottomBeat();
        //2. 找到选中note最小beat值
        var notes = [];
        var len = this.select.length;
        var _min = [99999999, 0, 1];
        for(var i=0;i<len;i++){
            var _id = +this.select.eq(i).data('tag');
            var _note = this.ui.manager.getNote(_id);
            notes.push(_note); //为了省事, notes和select完全对应
            if(frac.compare(_note.beat, _min) < 0){
                _min = _note.beat;
            }
        }
        //3. 计算beat差, 全部note加上这个差值
        var delta = frac.subtract(beat, _min);
        for(var i=0;i<len;i++){
            var _note = notes[i];
            _note.beat = frac.add(_note.beat, delta);
            if(_note.endbeat){
                _note.endbeat = frac.add(_note.endbeat, delta);
            }
            var time = timing.beatToTime(_note.beat) + (_note.offset || 0);
            if(_note.tid){
                sound.offsetCell(_note.tid, time);
            }
            this.ui.alignNote(_note, this.select.eq(i));
            this.ui.checkMaxTime(time);
        }
        event.trigger(event.events.note.change);
    }
};

module.exports = ret;